<template>
  <div id="categories">
    <!-- 1、导航 -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、卡片 -->
    <el-card>
      <!-- 2-1 添加按钮 -->
      <el-button type="primary" :icon="Plus" @click="showAddDialog"
        >添加分类</el-button
      >
      <!-- 2-2 分类表格 -->
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="cat_id"
        border
        stripe
        :default-expand-all="false"
        :header-cell-style="header_cell_style"
      >
        <el-table-column prop="cat_name" label="分类名称" />
        <el-table-column label="是否可用" align="center">
          <template v-slot="props">
            <el-icon v-if="props.row.cat_deleted"
              ><circleCloseFilled
            /></el-icon>
            <el-icon v-else><circleCheckFilled /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="分类级别" align="center">
          <template v-slot="props">
            <el-tag v-if="props.row.cat_level === 0" effect="dark"
              >一级分类</el-tag
            >
            <el-tag
              v-else-if="props.row.cat_level === 1"
              type="success"
              effect="dark"
              >二级分类</el-tag
            >
            <el-tag v-else type="warning" effect="dark">三级分类</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button
              type="primary"
              :icon="EditPen"
              @click="showUpdateDialog(scope.row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              :icon="Delete"
              @click="deleteCate(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2-3 分页器 -->
      <el-pagination
        :currentPage="pagenum"
        :page-size="pagesize"
        :page-sizes="[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 3、添加分类对话框 -->
    <el-dialog
      v-model="addCatesDialogVisible"
      title="添加分类"
      width="50%"
      @close="reset(addRef)"
    >
      <el-form ref="addRef" :model="addForm" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name" size="large" />
        </el-form-item>
        <el-form-item label="分类级别">
          <el-cascader
            style="width: 100%"
            v-model="addForm.cat_ids"
            :options="options"
            :props="props"
            size="large"
            :clearable="true"
            change-on-select
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitAdd(addRef)">确认</el-button>
          <el-button type="primary" @click="addCatesDialogVisible = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 4、修改分类 -->
    <el-dialog
      v-model="updateCatesDialogVisible"
      title="修改分类"
      width="50%"
      @close="reset(updateRef)"
    >
      <el-form
        ref="updateRef"
        :model="updateForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="updateForm.cat_name" size="large"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer"
          ><el-button @click="submitUpate(updateRef)">确认</el-button>
          <el-button type="primary" @click="updateCatesDialogVisible = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import request from "@/utils/request.js";
import {
  ArrowRight,
  EditPen,
  Delete,
  Plus,
  CircleCheckFilled,
  CircleCloseFilled,
} from "@element-plus/icons-vue";
import { error, success, confirm, info } from "@/utils/message";
const header_cell_style = {
  backgroundColor: "#00A0FF",
  color: "#fff",
  textAlign: "center",
};
const pagenum = ref(1);
const pagesize = ref(5);
const tableData = ref([]);
const total = ref(0);
const addCatesDialogVisible = ref(false);
const updateCatesDialogVisible = ref(false);
const updateRef = ref();
const addRef = ref();
const updateForm = reactive({
  cat_name: "",
  cat_id: 0,
});
const rules = ref({
  cat_name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 15, message: "分类名称长度 2 到 15字符", trigger: "blur" },
  ],
});
//cascader 的配置项
let props = reactive({
    expandTrigger: "hover",
    value: "cat_id",
    label: "cat_name",
    children: "children",
    checkStrictly: true,
  }),
  // cascader的数据源
  options = ref([]),
  addForm = reactive({
    cat_name: "",
    cat_ids: [],
    cat_pid: 0,
  });

/*--------------------------------定义函数---------------------------------*/
// 修改分类
async function updateCate() {
  let option = {
    url: `categories/${updateForm.cat_id}`,
    type: "put",
    data: { cat_name: updateForm.cat_name },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    updateCatesDialogVisible.value = false;
    getCateList();
  } catch (error) {
    console.log(error);
  }
}
// 提交分类修改请求
function submitUpate(form) {
  form.validate((v) => {
    v && updateCate();
  });
}
//重置表单
function reset(form) {
  form.resetFields();
}
// 点击显示修改对话框
function showUpdateDialog(cate) {
  Object.assign(updateForm, cate);
  updateCatesDialogVisible.value = true;
}
// 删除指定的分类
function deleteCate(cate) {
  confirm("确定要永久删除当前分类", "删除分类", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let option = {
        url: `categories/${cate.cat_id}`,
        type: "delete",
      };
      try {
        let { data: res } = await request(option);
        if (res.meta.status !== 200) {
          return error(res.meta.msg);
        }
        success(res.meta.msg);
        getCateList();
      } catch (error) {
        console.log(error);
      }
    })
    .catch(() => {
      info("您取消了删除");
    });
}
// 添加分类
async function addCate() {
  let cat_level = addForm.cat_ids.length;
  let cat_pid = addForm.cat_ids.length
    ? addForm.cat_ids[addForm.cat_ids.length - 1]
    : 0;
  let option = {
    url: "categories",
    type: "post",
    data: {
      cat_pid,
      cat_name: addForm.cat_name,
      cat_level,
    },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 201) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    addCatesDialogVisible.value = false;
    getCateList();
  } catch (error) {
    console.log(error);
  }
}
function submitAdd(form) {
  form.validate((v) => {
    v && addCate();
  });
}
// 获得一，二级分类的列表
async function getCateL2() {
  let option = {
    url: "categories",
    type: "get",
    data: { type: 2 },
  };
  try {
    let { data: res } = await request(option);
    console.log(res);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    options.value = res.data;
  } catch (error) {
    console.log(error);
  }
}
function showAddDialog() {
  // 请求分类列表
  getCateL2();
  //
  addCatesDialogVisible.value = true;
}
function handleSizeChange(size) {
  pagesize.value = size;
  pagenum.value = 1;
  getCateList();
}
function handleCurrentChange(num) {
  pagenum.value = num;
  getCateList();
}
async function getCateList() {
  let option = {
    url: "categories",
    type: "get",
    data: { pagenum: pagenum.value, pagesize: pagesize.value },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    tableData.value = res.data.result;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
  }
}
onMounted(() => {
  getCateList();
});
</script>

<style scoped lang="scss">
.el-icon {
  color: green;
  font-size: 25px;
}
.el-card {
  margin: 20px 0;
}
.el-table {
  margin: 10px 0;
}
.el-pagination {
  float: right;
  margin-bottom: 15px;
}
</style>